package org.example.myleet.p1418;

import java.util.*;

public class Solution {
    public List<List<String>> displayTable(List<List<String>> orders) {
        Set<String> tableNumSet = new HashSet<>();
        Set<String> dishSet = new HashSet<>();
        for (List<String> order : orders) {
            tableNumSet.add(order.get(1));
            dishSet.add(order.get(2));
        }
        //获得桌子号
        List<String> tableNums = new ArrayList<>(tableNumSet);
        tableNums.sort(Comparator.comparingInt(Integer::parseInt));
        //记住桌子的行号
        Map<String, Integer> tableNumPositionMap = new HashMap<>();
        for (int i = 0; i < tableNums.size(); ++i) {
            tableNumPositionMap.put(tableNums.get(i), i);
        }
        //获得菜品列
        List<String> dishes = new ArrayList<>(dishSet);
        dishes.sort(String::compareTo);
        dishes.add(0, "Table");
        //记住菜品的列位置
        Map<String, Integer> dishPositionMap = new HashMap<>();
        for (int i = 1; i < dishes.size(); ++i) {
            dishPositionMap.put(dishes.get(i), i);
        }
        //结果表格（数字版）
        int[][] table = new int[tableNums.size()][dishes.size()];
        for (int i = 0; i < tableNums.size(); ++i) {
            table[i][0] = Integer.parseInt(tableNums.get(i));
        }
        for (List<String> order : orders) {
            int rowIdx = tableNumPositionMap.get(order.get(1));
            int colIdx = dishPositionMap.get(order.get(2));
            ++table[rowIdx][colIdx];
        }
        //结果表格（字符串版）
        List<List<String>> result = new ArrayList<>();
        //表头
        result.add(dishes);
        for (int i = 0; i < table.length; ++i) {
            List<String> row = new ArrayList<>();
            for (int integer : table[i]) {
                row.add(String.valueOf(integer));
            }
            result.add(row);
        }
        return result;
    }
}
